$(function () {
    xsd_init();
})


function xsd_init() {
    //销售单位加载
//    $('#xsdSbdw').combotree({
//        loadFilter:function (rows) {
//            return convert(rows);
//        },
//        onSelect:function (record) {
//            $('#xsdSbr').combobox({
//                url:$.webPath() + '/sys/yg/ygXmList?zgjgId=' + record.id,
//                valueField:'id',
//                textField:'xm'
//            });
//        }
//    });
    $("[name='xsd_sbgs']").jgbmtree($("[name='xsd_sbbm']"), $("[name='xsd_sbr']"), '', '')
    //客户加载
    $("[name='xsd_kh']").qyjgzcombobox();
    //工程加载
    /*  $("[name='xsd_gc']").cxgccombobox();*/
    var options = getXsdGridOption();
    $('#xsd-grid').datagrid(options);
}

function xsd_search() {
    var zt = $("#xsd-toolbar input[name='xsd_zt']").val();
  //  var zt = "ybc";
    var xsdh = $("#xsd-toolbar input[name='xsd_xsdh']").val();
    var kh = $("#xsd-toolbar input[name='xsd_kh']").val();
    //var sbdw = $("#xsd-toolbar input[name='xsdSbdw']").val();
    var sbgs = $("#xsd-toolbar input[name='xsd_sbgs']").val();
    var sbbm = $("#xsd-toolbar input[name='xsd_sbbm']").val();
    var sbr = $("#xsd-toolbar input[name='xsd_sbr']").val();
    var gc = $("#xsd-toolbar input[name='xsd_gc']").val();
    var fhsjStart = $('#fhrq_start').datebox('getValue');
    var fhsjEnd = $('#fhrq_end').datebox('getValue');
    var dlkhxsd = ($("#xsd_dlkhxsd").attr("checked") == 'checked');
    var options = $.extend(getXsdGridOption(),
        {pageNumber: 1, queryParams: {zt: zt, xsdh: xsdh, khId: kh, sbgsId: sbgs, sbbmId: sbbm, sbrId: sbr, gcId: gc, fhsjStart: fhsjStart, fhsjEnd: fhsjEnd, dlkhxsd: dlkhxsd}});
    $('#xsd-grid').datagrid(options);
}

//新建之前选择销售类型
function xslx_xz(title, action) {
//    var href = $.webPath() + "/xsgl/xsdgl/xsd_xslx";
//    xslx_showDialog(title, href);
    var title = "新增销售单";
    var href = $.webPath() + "/xsgl/xsdgl/xsdgl_content?xslx=htxs";// + $("input[name='xsd.xslx']:checked").val();
    xsdhref = $.webPath() + "/xsgl/xsdgl/add_xsd";
    xsd_showDialog(title, href);
}

var xslx_win, xsdhref;
function xslx_showDialog(title, href) {
    var button = [
        {text: '确认', handler: function () {
            var title = "新增销售单";
            var href = $.webPath() + "/xsgl/xsdgl/xsdgl_content?xslx=" + $("input[name='xsd.xslx']:checked").val();
            xsdhref = $.webPath() + "/xsgl/xsdgl/add_xsd";
            $(xslx_win).window('close');
            xsd_showDialog(title, href);
        }}
    ];
    xslx_win = $.window({
        title: title,
        iconCls: 'icon-add2',
        url: href,
        width: 200,
        height: 220,
        buttons: button
    });
}

var xsd_xdxk;
function xsd_sdxk() {

    var record = $("#xsd-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要挂款的记录!", "info");
        return;
    }
    var buttons = [
        {text: '确认', handler: sdxk_saveItem}
    ];

    xsd_xdxk = $.window({
        title: '挂款',
        iconCls: 'icon-add2',
        url: $.webPath() + "/xsgl/xsdgl/sdxk_content?xsdId=" + record.id,
        width: 1024,
        height: 505,
        buttons: buttons
    })

//    $.messager.confirm('确认', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;是否进行手动选款?<br/>(确认)进入手动选款/(取消)系统自动挂款', function (r) {
//        if (r) {//手动选款
//            var buttons = [
//                {text: '确认', handler: sdxk_saveItem}
//            ];
//
//            xsd_xdxk = $.window({
//                title: '挂款',
//                iconCls: 'icon-add2',
//                url: $.webPath() + "/xsgl/xsdgl/sdxk_content?xsdId=" + record.id,
//                width: 1024,
//                height: 505,
//                buttons: buttons
//            })
//        } else {//自动选款
//            $("#main_index_center").mask();
//            $.post($.webPath() + '/xsgl/xsdgl/xsdgl_sfkpk', {xsdId: record.id}, function (data) {
//                var obj = eval('(' + data + ')');
//                $("#main_index_center").mask('hide');
//                $("#main_index_center").children(".mask").hide();
//                $("#main_index_center").children(".mask-msg").hide();
//                $('#xsd-grid').datagrid('reload');
//                $.messager.alert('提示', obj.message, 'info');
//            });
//        }
//    })

}

function sdxk_saveItem() {
    $("xsd_xdxk").mask();
    $('#sdxkForm').tabs('select', "销售信息");
    $.messager.progress();
    $("#sdxkForm").form('submit', {
        url: $.webPath() + "/xsgl/xsdgl/xsdgl_sfkpk?dqtxxx=" + $("#dqtx").val() + "&zjzyf=" + $("#zjzyf").val() + '&',
        onSubmit: function (param) {
            var data = $('#sdxk_table').edatagrid("getChecked");
            if (!data.length) {
                $.messager.progress('close');
                $("xsd_xdxk").mask('hide');
                $('#sdxkForm').tabs('select', "销售信息");
                $.messager.alert("提示", "请勾选要挂的收款!", "waring");
                return false;
            }
            var arrayPrefix = 'xsd.skList';

            var paramString = "{";
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                var objectString = $.toJSONStringSubPrefix(obj, arrayPrefix + "[" + i + "].", ['id']);
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            }

            if (data && data.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success: function (data) {
            $.messager.progress('close');
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $("xsd_xdxk").mask('hide');
                $(xsd_xdxk).window('close');
                $('#xsd-grid').datagrid('reload');
                $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
            } else {
                $("xsd_xdxk").mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}


function xsd_editItem(title, action) {
    var record = $("#xsd-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的记录!", "info");
        return;
    }
    var href = $.webPath() + "/xsgl/xsdgl/xsdgl_content?xsdId=" + record.id;
    xsdhref = $.webPath() + "/xsgl/xsdgl/" + action;
    xsd_showDialog(title, href);
}

//新增、修改销售单弹出界面
var xsd_win;
function xsd_showDialog(title, href) {
    var button = [
        {text: '保存', handler: xsd_saveItem}
    ];

    xsd_win = $.window({
        title: title,
        iconCls: 'icon-add2',
        url: href,
        width: 1024,
        height: 505,
        buttons: button
    });
}


function xsd_saveItem() {
    $("xsd_win").mask();
    $("#xsd_mx").edatagrid('saveRow');
    $("#xsd_fy").edatagrid('saveRow');
    $('#xsdglForm').tabs('select', "销售信息");
    $("#xsdglForm").form('submit', {
        url: xsdhref,
        onSubmit: function (param) {
            var data = $('#xsd_mx').edatagrid("getChecked");
            /* var fydata = $('#xsd_fy').edatagrid("getData");*/
            if ($("#xsd_kh_id").val() == "") {
                $("xsd_win").mask('hide');
                $.messager.alert("提示", "客户必须填写!", "waring");
                return false;
            }

            if (!data.length) {
                $("xsd_win").mask('hide');
                $('#xsdglForm').tabs('select', "销售明细");
                $.messager.alert("提示", "请勾选销售明细!", "waring");
                return false;
            }
            if ($("[name='xsd.xslx']").val() == "kcls" && $("#xsd_lj_id").length > 0) {
                var xtsl = $("#xsd_lj_sl").val();
                var sumsl = 0;
                for (var i = 0; i < data.length; i++) {
                    var sl = parseFloat(data[i]['sbsl']);
                    sl = isNaN(sl) ? 0 : sl;
                    sumsl += sl;
                }
                if (sumsl > xtsl) {
                    $.messager.alert("提示", "库存零售重量不得大于路径设定重量!", "waring");
                    return false;
                }
            }

//            if (xsfy == '我方承担销售费用') {
//                if (!fydata.rows.length) {
//                    $('#xsdglForm').tabs('select', "费用明细");
//                    $.messager.alert("提示", "请填写销售费用!", "waring");
//                    return false;
//                }
//            }
            var arrayPrefix = 'xsd.xsmxList';
            /* var fyPrefix = 'xsd.xsfyList';
             */
            var kcentiry = {};
            var paramString = "{";
            for (var i = 0; i < data.length; i++) {
                /* if (data.rows[i].js == 0 || data.rows[i].js == null) {
                 $("xsd_win").mask('hide');
                 $('#xsdglForm').tabs('select', "销售明细");
                 $.messager.alert('提示', '第' + (i + 1) + '行的件数不能为0 !', 'info');
                 return false;
                 }*/

                var obj = data[i];
                if ($("[name='xsd.xslx']").val() != "zddh") {
                    if ((obj['kh.id'] == undefined || obj['kh.id'] == '')) {
                        $("xsd_win").mask('hide');
                        $('#xsdglForm').tabs('select', "销售明细");
                        $.messager.alert("提示", "请选择卡号!", "waring");
                        return false;
                    } else {
                        var sl = 0;
                        if (kcentiry['s' + obj['kh.id']] != null) {
                            sl = parseFloat(kcentiry['s' + obj['kh.id']]) - parseFloat(obj['sbsl'].toString());
                        } else {
                            sl = parseFloat(obj['kkdsl'].toString()) - obj['sbsl'];
                        }
                        if (sl >= 0) {
                            kcentiry['s' + obj['kh.id']] = sl;
                        } else {
                            $('#xsdglForm').tabs('select', "销售明细");
                            $.messager.alert("提示", "库存不够!", "waring");
                            return false;
                        }
                    }
                }
                var objectString = $.toJSONStringSubPrefix(obj, arrayPrefix + "[" + i + "].", ['jzfs.id', 'jzfs.z', 'hsj', 'bhsj', 'bz', 'sbsl', 'js', 'kh.id', 'xscb', 'ck', 'mxh',
                    ['wzgg.id', 'jtwz.id'],
                    ['wzgg.code', 'jtwz.code'],
                    ['wzgg.name', 'jtwz.name'],
                    ['wzgg.ggxh', 'jtwz.ggxh'],
                    ['wzgg.dw', 'jtwz.dw']]);
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            }
            //费用物资计划
            /*  for (var i = 0; i < fydata.rows.length; i++) {
             {
             var objectString = $.toJSONStringPrefix(fydata.rows[i], fyPrefix + "[" + i + "].");
             paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
             }
             }*/
            if (data && data.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success: function (data) {
            //$("xsd_win").mask('hide');
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $("xsd_win").mask('hide');
                $(xsd_win).window('close');
                $('#xsd-grid').datagrid('reload');
//                $('#xsd_layout').layout('panel', 'center').panel('refresh');
                $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
            } else {
                $("xsd_win").mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function xsd_destroyItem() {
    var row = $('#xsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认删除此销售单', function (r) {
            if (r) {
                var index = $('#xsd-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/xsgl/xsdgl/delete_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsd-grid').datagrid('reload');
//                        $('#xsd_layout').layout('panel', 'center').panel('refresh');
                    } else {
                        $.messager.alert('提示', obj.message, 'info');
                    }
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的销售单", 'info');
    }
}

function xsd_commitItem() {
    var row = $('#xsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否执行过户', function (r) {
            if (r) {
                $("#main_index_center").mask();
//                $("#xsd-commit").parent().parent().parent().parent().parent().mask();
                $.post($.webPath() + '/xsgl/xsdgl/commit_xsd?comType=transfer', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $("#main_index_center").mask('hide');
                        $("#main_index_center").children(".mask").hide();
                        $("#main_index_center").children(".mask-msg").hide();
//                        $("#xsd-commit").parent().parent().parent().parent().parent().mask('hide');
                        $('#xsd-grid').datagrid('reload');
                    } else {
                        $("#main_index_center").mask('hide');
                        $("#main_index_center").children(".mask").hide();
                        $("#main_index_center").children(".mask-msg").hide();
//                        $("#xsd-commit").parent().parent().parent().parent().parent().mask('hide');
                        $('#xsd-grid').datagrid('reload');
                        $.messager.alert('提示', obj.message, 'info');
                    }

                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要过户的销售单", 'info');
    }
}

function xsd_cancelItem() {
    var row = $('#xsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否取消提交此销售单', function (r) {
            if (r) {
                $.post($.webPath() + '/xsgl/xsdgl/cancel_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200')
                        $('#xsd-grid').datagrid('reload');
                    else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要取消提交的销售单", 'info');
    }
}

// 审核
function xsd_examineItem() {
    var record = $("#xsd-grid").datagrid("getSelected");
    if (record) {
        $.messager.confirm('提示', '是否确认审核该出库单？', function (r) {
            if (r) {
                $.ajax({
                    url: $.webPath() + "/xsgl/xsdgl/examine_xsd",
                    dataType: 'json',
                    type: 'POST',
                    data: {xsdId: record.id},
                    success: function (data) {
                        if (data.statusCode == 200) {
                            $('#xsd-grid').datagrid('reload');
                            $.messager.show({
                                title: '提示',
                                msg: data.message,
                                timeout: 3000,
                                showType: 'slide'
                            });
                        } else {
                            $.messager.alert("提示", data.message, "error");
                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选择要审核的出库单！", "warning");
    }
}


function getXsdGridOption() {
    var options = {
        url: $.webPath() + "/xsgl/xsdgl/xsdList?sftzd=false",
        toolbar: "#xsd-toolbar",
        fitColumns: true,
        singleSelect: true,
        pageNumber: 1,
        pagination: true,
        fit: true,
        rownumbers: true,
        showFooter: true,
        onLoadSuccess: function (target) {
            $("#xsd-del").css('display', 'none');
            $("#xsd-edit").css('display', 'none');
            $("#xsd-commit").css('display', 'none');
            $(this).datagrid('selectRow', 0);

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        loadFilter: function (data) {
            $.each(data.rows, function () {
                if (this.xslx) {
                    this.xslx = this.xslx == 'htxs' ? "合同销售" : this.xslx == 'zddh' ? "直达到货" : this.xslx == 'bgxs' ? "保供销售" : "库存零售";
                }
            })
            return data;
        },
        onSelect: function (rowIndex, rowData) {
            if (!rowData) {
                $("#xsd-edit").hide();
                $("#xsd-del").hide();
                $("#xsd-commit").hide();
                $("#xsd_jz").hide();
                $("#btn_cancel_xsd").show();
                $("#xsd-cbjgtz").hide();
                $("#xsd-pk").hide();
                $("#xsd-sdxk").hide();
                $("#xsd-self").hide();
                $("#xsd_examine").hide();
                return;
            }
            if (rowData && rowData.yck && rowData.xslx != '保供销售') {
                $("#xsd-cbjgtz").hide();
            } else {
                $("#xsd-cbjgtz").hide();
            }
            if (rowData && rowData.zt == 'ybc') {
                $("#xsd-edit").show();
                $("#xsd_jz").hide();
                $("#xsd-del").show();
                $("#xsd-commit").hide();
                $("#btn_cancel_xsd").hide();
                $("#xsd-examine").hide();
                $("#xsd-pk").hide();
                $("#xsd-self").hide();
                $("#xsd-sdxk").show();
//                $("#xsd_examine").show();
            }
//            else if (rowData && rowData.zt == 'ysh') {
//                $("#xsd-edit").hide();
//                $("#xsd_jz").hide();
//                $("#xsd-del").hide();
//                $("#xsd-commit").hide();
//                $("#btn_cancel_xsd").hide();
//                $("#xsd-examine").hide();
//                $("#xsd-pk").hide();
//                $("#xsd-self").hide();
//                $("#xsd-sdxk").show();
//                $("#xsd_examine").hide();
//            }
            else {
                $("#xsd_jz").hide();
                $("#xsd-edit").hide();
                $("#xsd-del").hide();
                $("#xsd-commit").hide();
                $("#btn_cancel_xsd").hide();
                $("#xsd-examine").hide();
                $("#xsd-pk").hide();
                $("#xsd-sdxk").hide();
                $("#xsd-self").hide();
                $("#xsd_examine").hide();
            }
        }, onDblClickCell: function (index, field, value) {
            if (field == "xsdh") {
                $("#xsd-edit:visible").click();
            }
        }
    }

    var columns = {columns: [
        [
            {field: 'xsdh', title: '销售单号', align: 'center', width: 50, formatter: xsdCell},
            {field: 'xslx', title: '销售类型', align: 'center', width: 30},
            {field: 'fhsj', title: '发货日期', align: 'center', width: 35},
            {field: 'sxsj', title: '制单日期', align: 'center', width: 35},
            {field: 'kh_jc', title: '客户名称', align: 'center', width: 50},
            {field: 'xsjs', title: '销售件数', align: 'right', width: 50,
                formatter: function (value) {
                    var sl = formatSlForHtml(value, ",");
                    return sl;
                }
            },
            {field: 'xssl', title: '销售重量', align: 'right', width: 50,
                formatter: function (value) {
                    var sl = formatSlForHtml(value, ",");
                    return sl;
                }
            },
            {field: 'xsje', title: '销售总金额(元)', align: 'right', width: 50,
                formatter: function (value) {
                    var sl = formatJeForHtml2(value, ",");
                    return sl;
                }
            },
            {field: 'fyzr_z', title: '配送类型', align: 'center', width: 25},
//            {field: 'gylfyje', title: '配送费用(元)', align: 'right', width: 50,
//                formatter: function (value) {
//                    var sl = formatJeForHtml2(value, ",");
//                    return sl;
//                }
//            },
//            {field: 'gc_mc', title: '工程', align: 'center', width: 30},
            {field: 'sbr_xm', title: '申报人', align: 'center', hidden: true},
            {field: 'orderId', title: '来源类型', align: 'center', width: 25, formatter: function (value) {
                if (value)
                    return "线上";
                return "线下";
            }},
            {field: 'xsgs_jc', title: '销售公司', align: 'center', width: 30},
            {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 25},
            {field: 'sbbm_jc', title: '申报部门', align: 'center', hidden: true},
            {field: 'sbr_xm', title: '申报人', align: 'center', hidden: true},
            {field: 'zt', title: '状态', width: 20, align: 'center', formatter: function (value, rowData) {
                if (value == 'ybc')
                    return '已保存';
                if (value == 'ysh')
                    return '已审核';

            }}
        ]
    ]}
    options = $.extend(options, columns);
    return options;
}
//成本价格调整
function xsd_cbjgtz() {
    var row = $('#xsd-grid').datagrid('getSelected');
    if (row) {
        var button = [
            {text: '确定', handler: function () {
                $("#xsd_cbjgtz_xsdmx_table").edatagrid('saveRow');
                $("#xsd_cbjgtz_form").form('submit', {
                    onSubmit: function (param) {
                        var data = $("#xsd_cbjgtz_xsdmx_table").edatagrid('getRows');
                        for (var i = 0; i < data.length; i++) {
                            param['xsd.xsmxList[' + i + '].id'] = data[i].id;
                            param['xsd.xsmxList[' + i + '].xscb'] = data[i].xscb;
                        }
                        return true;
                    },
                    success: function (data) {
                        var obj = eval('(' + data + ')');
                        if (obj.statusCode == '200') {
                            $(xsd_win).window('close');
                            $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                        } else {
                            $.messager.alert('提示', obj.message, 'info');
                        }
                    }
                });
            }}
        ];

        xsd_win = $.window({
            title: '销售成本调整',
            iconCls: 'icon-save',
            url: $.webPath() + "/xsgl/xsdgl/xsd_cbjgtz?xsdId=" + row.id,
            width: 1024,
            height: 505,
            buttons: button
        });
    } else {
        $.messager.alert('提示', "请选择销售单", 'info');
    }
}

function xsd_JzItem() {
    var row = $('#xsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认解质此销售单', function (r) {
            if (r) {
                $.post($.webPath() + '/xsgl/xsdgl/jz_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                        $('#xsd-grid').datagrid('reload');
                    } else {
                        $.messager.alert('提示', obj.message, 'info');
                    }
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要解质的销售单", 'info');
    }
}